#include "friendmodel.hpp"

#include "db.h"    // 数据层的操作头文件  包含了MySQL类
#include <sstream> // 包含 ostringstream 的定义

// 添加好友关系
void FriendModel::insert(int userid, int friendid)
{
    // 1.组装sql语句
    std::ostringstream sql;
    sql << "insert into Friend values(" << userid << ", " << friendid << ")";

    MySQL mysql;
    if (mysql.connect())
    {
        mysql.query(sql.str());
    }
}

// 返回用户好友列表:
std::vector<User> FriendModel::query(int userid)
{
    // 1.组装sql语句
    std::ostringstream sql;
    sql << "SELECT a.id, a.name, a.state FROM User a INNER JOIN Friend b ON b.friendid = a.id WHERE b.userid = " << userid;

    std::vector<User> vec;
    MySQL mysql;
    if (mysql.connect())
    {
        MYSQL_RES *res = mysql.query(sql.str());
        MYSQL_ROW row;
        while ((row = mysql_fetch_row(res)) != nullptr)
        {
            User user;
            if (row[0] != nullptr)
            {
                user.setId(std::stoi(row[0]));
            }
            if (row[1] != nullptr)
            {
                user.setName(row[1]);
            }
            if (row[2] != nullptr)
            {
                user.setState(row[2]);
            }
            vec.push_back(user);
        }
        mysql_free_result(res); // 释放结果集!!!
        return vec;
    }
    return vec;
}
